package com.ykzhujiang.lovespirit;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;

import javax.jdo.PersistenceManager;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.ykzhujiang.lovespirit.entity.LSUser;
import com.ykzhujiang.lovespirit.util.DataManager;
import com.ykzhujiang.lovespirit.util.PMF;

public class SubscribeServlet extends HttpServlet {
	private static final Logger logger = Logger
			.getLogger(SubscribeServlet.class.getName());

	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();

		int type = -1;
		try {
			type = Integer.parseInt(req.getParameter("t"));
		} catch (NumberFormatException e) {
		}
		if (user == null
				|| (type != LSUser.TYPE_REG && type != LSUser.TYPE_UNREG)) {
			resp.sendRedirect("/");
			return;
		}

		if (type == LSUser.TYPE_REG) {
			logger.info("try to add lsuser");
			if (DataManager.getData(LSUser.class, user.getEmail(), false, null) == null) {
				DataManager.addData(new LSUser(user.getEmail(), user,
						new Date(), new Date(0), type));
			} else {
				logger.warning("lsuser exist");
			}

		} else if (type == LSUser.TYPE_UNREG) {
			logger.info("try to delete lsuser");
			DataManager.removeData(LSUser.class, user.getEmail());
		}

		resp.sendRedirect("/");
	}
}